<?php
/**addroom
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-08-21
 * Time: 16:55
 */
namespace App\Http\Controllers\Mobile\Room;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\CustomersVail;
use App\Model\Account\SystemType;
use App\Model\Backstage\RoomFollow;
use App\Model\Backstage\RoomWordbook;
use App\Model\Mobile\MobilePlan;
use Illuminate\Http\Request;
use App\Model\Backstage\Customers;
use App\Model\Backstage\RoomInfo;
use App\Http\Controllers\Validator\RoomInfoVail;
use App\Tool\Error;
use Illuminate\Support\Facades\DB;
use Validator;

class RoomController extends Controller
{
    /**
     *  移动端房源列表
     */
    public function AppRoomList(Request $request,RoomInfo $roomInfo)
    {
        $param = $request->except('apptoken');
        $validator = CustomersVail::condition($param);
        if (!$validator){
            return $this->error(Error::PARAM_MISSING);
        }
        $where = [];
        //房源状态等于1 未删除房源
        $where[] = ['room_status',1];
        $authories = explode(',', $request->input('authories'));//该员工拥有的所有权限
        //房源查看权限   全部 1  跨部 2   本部 3 本人 4
        if (in_array(2, $authories)){ //跨部
            $where[] = ['r_d_id', '<>', $param['system_id']];
        } elseif (in_array(3, $authories)){//本部
            $where[] = ['r_d_id', '=', $param['did']];
        } elseif (in_array(4, $authories)){//本人
            $where[] = ['source_uid', '=', $param['uid']];
        }
        //日期 根据委托时间查询
        //委托时间 开始时间
        if ($request->input('start_time')) {
            $where[] = ['r_entrust_at', '>=', strtotime($param['start_time'].' 00:00:00')];
        } else {
            $where[] = ['r_entrust_at', '>=', strtotime(date('Y-m-d',strtotime('-12 month')).' 00:00:00')];
        }
        //交易类型  1 出售93  售低价最小值--最大值    2 出租94  租低价 最小值----最大值
        if($request->input('c_trading_type')){
            if ($request->input('c_trading_type') == 1 ) {
                $where[] = ['trading_type', '<>', 94];//类型 出售和租售
                if($request->input('small_price')){
                    $where[] = ['price', '>=', $param['c_price_min']];
                }
                if($request->input('big_price')){
                    $where[] = ['price', '<=', $param['c_price_max']];
                }
            }
            if ($request->input('c_trading_type') == 2 ) {
                $where[] = ['trading_type', '<>', 93];//类型 出租和租售
                if($request->input('small_price')){
                    $where[] = ['rents', '>=', $param['c_price_min']];
                }
                if($request->input('big_price')){
                    $where[] = ['rents', '<=', $param['c_price_max']];
                }
            }
        }
        //用途 1 住宅、商住   2 写字楼
        if ($request->input('c_use_type') == 1){
            $where[] = ['use_type', '<=', 4];
        } elseif ($request->input('c_use_type') == 2) {
            $where[] = ['use_type',  7];
        }
        //房型
        if($request->input('c_room')){
            $where[] = ['ri_room_type' , $param['c_room']];
        }

        //配置  1空   2 部分   3全部  furniture 家具
        if ($request->input('configuration') == 1) {
            $where[] = ['furniture',  189];
        } else if ($request->input('configuration') == 2) {
            $where[] = ['furniture',  '>=', 190];
            $where[] = ['furniture',  '<=', 191];
        } else if ($request->input('configuration') == 3) {
            $where[] = ['furniture',  193];
        }
        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        $list = $roomInfo->listRoom(env('PAGE_LIMIT_INDEX'), $where, $keywords, 1);//传1  是APP 端的;
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        $roomWordbook = new RoomWordbook();
        $mobilePlan = new MobilePlan();
        $follow = new RoomFollow();
        foreach($list as $k=>$v){
            $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
            if (!in_array(51, $authories) && $v->disc_type == 36 && $v->source_uid != $param['uid']) {//私盘
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话
            }
            if (!in_array(52, $authories) && $v->disc_type == 38 && $v->source_uid != $param['uid']) {//特盘
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话
            }
            if (!in_array(53, $authories) && $v->disc_type == 39 && $v->source_uid != $param['uid']) {//下定盘
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话
            }
            if (!in_array(54, $authories) && $v->disc_type == 708 && $v->source_uid != $param['uid']) {//斡旋盘
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话
            }
            if (!in_array(164, $authories) && $v->disc_type == 37 && $v->source_uid != $param['uid']) {//封盘
                $v->room_number = '****'; //房号
                $v->owner_name = '***'; //业主姓名
                $v->owner_phone = '***********'; //业主电话
                $v->contact_name = '***'; //联系人姓名
                $v->contact_phone = '***********'; //联系人电话
            }

            //如果是公盘   先根据是不是自己的房源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
            //看业主不必写跟进 162
            $v->lookStatus = 1;//lookStatus == 1不用写跟进   == 2 公盘可能需要写跟进
            if ($v->disc_type == 35 &&  $v->source_uid != $param['uid'] && !in_array(162, $authories)) {
                //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
                $res  = $follow->getFollowDay($v->id, $param['uid']);
//                //最后跟进的天  不是今天的话
                if ($res === 2) {
                    $v->lookStatus = $res;
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话;
                }
            }

            $v->r_entrust_at = $v->r_entrust_at != null ? date('Y-m-d',$v->r_entrust_at) : '';//委托时间
            $v->making_room = $v->making_room != null ? date('Y-m-d',$v->making_room) : '';//交房时间
            $v->building_s = $v->building_s != null ? date('Y',$v->building_s) : '';//建房年代
            $v->r_follow_time = $v->r_follow_time != null ? date('Y-m-d',$v->r_follow_time) : '';

            $v->use_name    = SystemType::getTypeDetail($v->use_type);         //用途
            $v->housing_name = SystemType::getTypeDetail($v->housing_types);  //房屋类型
            $v->type_of_house_name = SystemType::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
            $v->disc_name = SystemType::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
            $v->trading_name = SystemType::getTypeDetail($v->trading_type); //交易类型
            $v->trading_state_name = SystemType::getTypeDetail($v->status); //交易状态类型
            $v->rents_name = SystemType::getTypeDetail($v->rents_type);            //租价类型
            $v->taxes_fees_name = SystemType::getTypeDetail($v->taxes_fees);            //包税费类型
            $v->entrust_name = SystemType::getTypeDetail($v->entrust_way);    //委托方式
            $v->source_name = SystemType::getTypeDetail($v->source_type);    //来源id
            $v->status_quo_name = SystemType::getTypeDetail($v->status_quo);    //现状
            $v->decoration_name = SystemType::getTypeDetail($v->decoration);    //装修
            $v->furniture_name = SystemType::getTypeDetail($v->furniture);    //家具
            $v->appliance_name = SystemType::getTypeDetail($v->appliance);    //家电
            $v->rights_name = SystemType::getTypeDetail($v->rights_type);    //产权类型
            $v->certificate_name = SystemType::getTypeDetail($v->certificate_type);    //证件类型
            $v->payment_name = SystemType::getTypeDetail($v->payment_type);    //付款类型
            $v->pay_on_name = SystemType::getTypeDetail($v->pay_on_type);    //付拥类型
            $v->fence_type_name = SystemType::getTypeDetail($v->fence_type);    //围墙类型
            $v->wc_name = SystemType::getTypeDetail($v->wc_type);    //厕所类型
            $v->dorm_name = SystemType::getTypeDetail($v->dorm_type);    //宿舍类型
            $v->lot_name = SystemType::getTypeDetail($v->lot_type);    //地段类型
            $v->air_name = SystemType::getTypeDetail($v->air_type);    //空调类型
            $v->canteen_name = SystemType::getTypeDetail($v->canteen_type);    //食堂类型
            $v->checking_way_name = SystemType::getTypeDetail($v->checking_way);    //看房方式

            //多选框数据========配套
            $support_name = [];
            if($v->support){
                $support_arr = explode(',',$v->support);
                foreach($support_arr as $key => $val){
                    $support = SystemType::getTypeDetail($val);    //'配套
                    array_push($support_name, $support);
                }
            }
            $v->support_name = implode(',', $support_name);
            //多选框数据========行业
            $industry_name = [];
            if($v->industry_type){
                $industry_arr = explode(',',$v->industry_type);
                foreach($industry_arr as $key => $val){
                    $industry = SystemType::getTypeDetail($val);
                    array_push($industry_name, $industry);
                }
            }
            $v->industry_name = implode(',', $industry_name);
            //根据用途变换的输入款  将数据库json字符串转换成数组
            $v->r_info = json_decode($v->r_info, true);
            //房源明细列表
            $v->r_detaile_list = json_decode($v->r_detaile_list, true);
            //查标记
            $hmp_sign_type = $mobilePlan->getSignType(2, $v->id, $param['uid']);
            $v->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
        }
        $start_time = null;
        $end_time = strtotime(date('Y-m-d', time()).' 23:59:59');
        return $this->success('ok', $list, $start_time, $end_time);
    }

    /**
     *移动端  根据房源的id 获取该房源的跟进 RoomFollow $RoomFollow
     */
    public function getRoomFollow(Request $request, RoomFollow $RoomFollow){
        if($roomId = $request->input('f_room_id')){
//            $list = $RoomFollow->roomFollow($roomId, env('PAGE_LIMIT_ADMIN'), 1);
            $list = $RoomFollow->roomFollow($roomId, 3, 1);
            return $this->success('ok', $list);
        }
        return $this->error(Error:: PARAM_MISSING);

    }


    /**
     * 移动端新增房源
     */
    public function addRoom(Request $request,RoomInfo $RoomInfo){
        $params = $request->except('apptoken', 'industry_types', 'supports');
        $validator =  RoomInfoVail::validate($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $params['building_id'] = $RoomWordBook->getRoomId($params['building_id']);
        if (!$params['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $data = $RoomInfo->verificationRoomRepeat($params, 0);
        if ($data) {
            return $this->error(Error::REPEATED_ROOM);
        }
        //根据房源用途不同前台传的不同类型字段值,转换成json字符串，输出时直接转换成json数组前台取值
        $json_info = $request->input('r_info','{}');
//      $params['r_info'] = json_encode($json_info);
        $params['r_info'] = $json_info;
        //房源明细列表 将前台提交的明细数组转换成json 以name值为键 对应输入框值
        $json_detaile = $request->input('r_detaile_list','{}');
//        $params['r_detaile_list'] = json_encode($json_detaile);
        $params['r_detaile_list'] = $json_detaile;
        //建房年代
        if ($request->input('building_s')) {
            $params['building_s'] = strtotime($params['building_s'].'-01-01 00:00:00');
        }
        //委托时间
        if ($request->input('r_entrust_at')) {
            $params['r_entrust_at'] = strtotime($params['r_entrust_at']);
        } else {
            $params['r_entrust_at'] = time();
        }
        //交房时间
        if ($request->input('making_room')) {
            $params['making_room'] = strtotime($params['making_room']);
        }
        $params['r_created_at'] = time();//创建时间
        $params['r_updated_at'] = time(); //修改时间

        $rid = $RoomInfo->addRoomInfo($params);
        if (!$rid) {
            return $this->error(Error::ADD_ERROR);
        }
        return $this->success('ok', $rid);
    }

    /**
     * APP添加房源跟进
     */
    public function addFollow(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'f_department_id' => 'required',//部门ID
            'f_user_id'       => 'required',//员工ID
            'f_room_id'       => 'required',//房源ID
            'f_follow_up_way' => 'required',//跟进方式
            'f_content'       => 'required',//跟进内容
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        $follow = new RoomFollow();
        $params['cfs_remind_time'] = '';
        $params['cfs_user_id'] = '';
        $params['cfs_content'] = '';
        $cId = $follow->addRoomFollow($params,0);
        //开启事务
        DB::beginTransaction();
        $roomInfo = new RoomInfo();
        $saveTime = $roomInfo->updateFollowTime($params['f_room_id']);
        if($cId && $saveTime){
            DB::commit();
            return $this->success('ok', '添加成功！');
        } else {
            DB::rollback();
            return   $this->error(Error::ADD_ERROR);
        }
    }

    /**
     * 添加房源之前根据房源的区ID、楼盘字典  栋座  位置  查询该房源是不是重复录入
     */
    public function checkHouse(Request $request,RoomInfo $RoomInfo)
    {
        $params = $request->except('apptoken');
        $validator = Validator::make($params, [
            'building_id'                =>        'required',//楼盘字典名称
            'few_building'               =>        'required',//栋座
            'position'                   =>        'required', //位置
            'room_number'                =>        'required', //房号
            'authories'                  =>        'required', //权限
            'uid'                        =>        'required', //用户ID
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        $rId = 0;
        if ($request->input('r_id')) { //添加的时候没有房源的ID   修改的时候有房源ID
            $rId = $request->input('r_id');
        }
        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $params['building_id'] = $RoomWordBook->getRoomId($params['building_id']);
        if (!$params['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $data = $RoomInfo->verificationRoomRepeat($params, $rId);
        if (!$data) {
            return $this->error(Error::CHECK_HOUSE);
        }
        $data->province_code = $this->province_code;//省code
        $data->city_code = $this->city_code;//市CODE
        $data->city = $this->city;//市名字
//        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $data->r_entrust_at = date('Y-m-d', $data->r_entrust_at);//委托时间
        $data->making_room = date('Y-m-d', $data->making_room);//交房时间
        $data->building_s = date('Y', $data->building_s);
        $roomWordbook = new RoomWordbook();
        $data->building_name = $roomWordbook->getWordbook($data->building_id); //楼盘字典
        $data->use_name    = SystemType::getTypeDetail($data->use_type);         //用途
        $data->housing_name = SystemType::getTypeDetail($data->housing_types);  //房屋类型
        $data->type_of_house_name = SystemType::getTypeDetail($data->type_of_house_sale);  //房屋出售类型
        $data->disc_name = SystemType::getTypeDetail($data->disc_type);    //盘类型  私盘  公盘
        $data->trading_name = SystemType::getTypeDetail($data->trading_type); //交易类型
        $data->trading_state_name = SystemType::getTypeDetail($data->status); //交易状态类型
        $data->rents_name = SystemType::getTypeDetail($data->rents_type);            //租价类型
        $data->taxes_fees_name = SystemType::getTypeDetail($data->taxes_fees);            //包税费类型
        $data->entrust_name = SystemType::getTypeDetail($data->entrust_way);    //委托方式
        $data->source_name = SystemType::getTypeDetail($data->source_type);    //来源id
        $data->status_quo_name = SystemType::getTypeDetail($data->status_quo);    //现状
        $data->decoration_name = SystemType::getTypeDetail($data->decoration);    //装修
        $data->furniture_name = SystemType::getTypeDetail($data->furniture);    //家具
        $data->appliance_name = SystemType::getTypeDetail($data->appliance);    //家电
        $data->rights_name = SystemType::getTypeDetail($data->rights_type);    //产权类型
        $data->certificate_name = SystemType::getTypeDetail($data->certificate_type);    //证件类型
        $data->payment_name = SystemType::getTypeDetail($data->payment_type);    //付款类型
        $data->pay_on_name = SystemType::getTypeDetail($data->pay_on_type);    //付拥类型
        $data->fence_type_name = SystemType::getTypeDetail($data->fence_type);    //围墙类型
        $data->wc_name = SystemType::getTypeDetail($data->wc_type);    //厕所类型
        $data->dorm_name = SystemType::getTypeDetail($data->dorm_type);    //宿舍类型
        $data->lot_name = SystemType::getTypeDetail($data->lot_type);    //地段类型
        $data->air_name = SystemType::getTypeDetail($data->air_type);    //空调类型
        $data->canteen_name = SystemType::getTypeDetail($data->canteen_type);    //食堂类型
        $data->checking_way_name = SystemType::getTypeDetail($data->checking_way);    //看房方式
        //多选框数据循环查找======配套
        $support_name = [];
        if($data->support){
            $support_arr = explode(',',$data->support);
            foreach($support_arr as $key => $val){
                $support = SystemType::getTypeDetail($val);    //'配套
                array_push($support_name, $support);
            }
        }
        $data->support_name = implode(',', $support_name);
        //多选框数据========行业
        $industry_name = [];
        if($data->industry_type){
            $industry_arr = explode(',',$data->industry_type);
            foreach($industry_arr as $key => $val){
                $industry = SystemType::getTypeDetail($val);    //'配套
                array_push($industry_name, $industry);
            }
        }
        $data->industry_name = implode(',', $industry_name);

        //根据用途变换的输入款  将数据库json字符串转换成数组
        $data->r_info = json_decode($data->r_info, true);
        //房源明细列表
        $data->r_detaile_list = json_decode($data->r_detaile_list, true);
        $authories = explode(',', $request->input('authories'));//该员工拥有的所有权限
        if (!in_array(51, $authories) && $data->disc_type == 36 && $data->source_uid != $params['uid']) {//私盘
            $data->room_number = '****'; //房号
            $data->owner_name = '***'; //业主姓名
            $data->owner_phone = '***********'; //业主电话
            $data->contact_name = '***'; //联系人姓名
            $data->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(52, $authories) && $data->disc_type == 38 && $data->source_uid != $params['uid']) {//特盘
            $data->room_number = '****'; //房号
            $data->owner_name = '***'; //业主姓名
            $data->owner_phone = '***********'; //业主电话
            $data->contact_name = '***'; //联系人姓名
            $data->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(53, $authories) && $data->disc_type == 39 && $data->source_uid != $params['uid']) {//下定盘
            $data->room_number = '****'; //房号
            $data->owner_name = '***'; //业主姓名
            $data->owner_phone = '***********'; //业主电话
            $data->contact_name = '***'; //联系人姓名
            $data->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(54, $authories) && $data->disc_type == 708 && $data->source_uid != $params['uid']) {//斡旋盘
            $data->room_number = '****'; //房号
            $data->owner_name = '***'; //业主姓名
            $data->owner_phone = '***********'; //业主电话
            $data->contact_name = '***'; //联系人姓名
            $data->contact_phone = '***********'; //联系人电话
        }
        if (!in_array(164, $authories) && $data->disc_type == 37 && $data->source_uid != $params['uid']) {//封盘
            $data->room_number = '****'; //房号
            $data->owner_name = '***'; //业主姓名
            $data->owner_phone = '***********'; //业主电话
            $data->contact_name = '***'; //联系人姓名
            $data->contact_phone = '***********'; //联系人电话
        }

        //如果是公盘   先根据是不是自己的房源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
        //看业主不必写跟进 162
        if ($data->disc_type == 35 &&  $data->source_uid != $params['uid'] && !in_array(162, $authories)) {
            //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
            $follow = new RoomFollow();
            $res  = $follow->getFollowDay($data->id, $params['uid']);
//                //最后跟进的天  不是今天的话
            if ($res === 2) {
                $data->room_number = '****'; //房号
                $data->owner_name = '***'; //业主姓名
                $data->owner_phone = '***********'; //业主电话
                $data->contact_name = '***'; //联系人姓名
                $data->contact_phone = '***********'; //联系人电话;
            }
        }
        return $this->success('ok', $data);
    }

    /**
     * APP 写完公盘的跟进 根据房源的ID  查询该房源的重要信息
     */
    public function getData(Request $request,RoomInfo $roomInfo)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'id'          => 'required',//房源ID
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        return $this->success('ok', $roomInfo->getImportantInfo($request->input('id')));
    }
    /**
     * APP房源图片列表
     */
    //图片列表
    public function ImagesLists(Request $request,RoomInfo $roomInfo){
        if(!$request->input('id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $list = $roomInfo->AppImagesLists($request->input('id'));
        return $this->success('ok',$list);
    }
}

